ADD_CUSTOM_TARGET(CopyDLLs ALL COMMENT "Copying DLLs.")

MACRO(COPYINSTALL_DLLS SEARCH_DIRECTORY INSTALL_DIRECTORY DEBUG RELEASE INSTALL_)
  IF(WIN32 AND NOT UNIX)
      FOREACH(BASENAME ${ARGN})
		# find DLLs
		FILE(GLOB BINARIES "${SEARCH_DIRECTORY}/${BASENAME}*.dll")
		
		# loop through all found files
		FOREACH(BINARY ${BINARIES})
			# extract filename and extension
			GET_FILENAME_COMPONENT(FILENAME_WITH_EXT ${BINARY} NAME)

	        # copy
		    IF(MSVC)
		    	IF(${DEBUG})
	    			MESSAGE("Copying ${BINARY} to ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Debug/${FILENAME_WITH_EXT}.")
    				ADD_CUSTOM_COMMAND(TARGET CopyDLLs COMMAND ${CMAKE_COMMAND} -E copy
    				                   "${BINARY}"
    				                   "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Debug/${FILENAME_WITH_EXT}")
			    ENDIF(${DEBUG})
   				IF(${RELEASE})
			    	MESSAGE("Copying ${BINARY} to ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Release/${FILENAME_WITH_EXT}.")
    				ADD_CUSTOM_COMMAND(TARGET CopyDLLs COMMAND ${CMAKE_COMMAND} -E copy
    				                   "${BINARY}"
    				                   "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Release/${FILENAME_WITH_EXT}")
	    		ENDIF(${RELEASE})
    	    ENDIF(MSVC)
			    
   		  # install
   		  IF(INSTALL_)
	          INSTALL(FILES ${BINARY} DESTINATION ${INSTALL_DIRECTORY})
	      ENDIF(INSTALL_)
	  ENDFOREACH(BINARY)
	ENDFOREACH(BASENAME)
  ENDIF(WIN32 AND NOT UNIX)
ENDMACRO(COPYINSTALL_DLLS)